﻿using System;
using System.Configuration;
using System.DirectoryServices;

namespace TWA.TFS
{
    /// <summary>
    /// Tools for interacting with Active Directory
    /// </summary>
    internal class Directory
    {
        /// <summary>
        /// Retrieves a user's email address from Active Directory based on 
        /// their display name or null if no email address is configured for the user
        /// (e.g. the Unassigned user has no email address).
        /// <remarks>
        /// * Names as returned by TFS may vary in format; the event XML does not contain a straight account name.
        /// * Not all accounts have an email address assigned.
        /// </remarks>
        /// </summary>
        internal static string GetEmailAddress (string userDisplayName)
        {
            string adSearchFilter = ConfigurationManager.AppSettings ["ADSearchFilter"];
                                          
            var ds = new DirectorySearcher ();
            ds.PropertiesToLoad.Add ("mail");
            ds.Filter = String.Format (adSearchFilter, userDisplayName);

            SearchResult result = ds.FindOne ();

            if (result != null)
            {
                ResultPropertyValueCollection values = result.Properties ["mail"];

                if (values.Count > 0)
                {
                    string emailAddress = values [0].ToString ();
                    Logger.Log ("Found email address " + emailAddress + " for user " + userDisplayName);
                    return emailAddress;
                }
            }

            Logger.Log ("Failed to retrieve an email address for user " + userDisplayName);
            return null;
        }
    }
}